<?php

namespace app\index\controller;

use app\index\model\Cate;
use app\index\model\Question;
use app\index\model\Sign;
use think\Controller;
use think\Db;

class Index extends Controller
{
	public function index()
	{
		/**
		 * 查询分类
		 */
		$cate = Cate::all();
		$this->assign('cate', $cate);

		$where = [];
		input('cate_id') && $where = ['t3.cate_id' => input('cate_id')];

		input('type') == 1 && $where = ['t1.status' => '0'];

		input('type') == 2 && $where = ['t1.status' => '1'];

		input('type') == 3 && $where = ['t1.is_good' => '1'];

		/**
		 * 查出所有帖子
		 */
		$post = Db::name('question')
			->alias('t1')
			->field('t1.*,t2.face,t2.nickname,t2.user_id,t3.cate_name,t3.cate_id')
			->join('user t2', 't1.user_id = t2.user_id')
			->join('cate t3', 't1.cate_id = t3.cate_id')
			->order('t1.create_time desc')
			->where($where)
			->paginate(12);
		$this->assign('post', $post);

		/**
		 * 查询所有帖子置顶的帖子
		 */
		$is_top = Db::name('question')
			->alias('t1')
			->field('t1.*,t2.face,t2.nickname,t2.user_id,t3.cate_name,t3.cate_id')
			->join('user t2', 't1.user_id = t2.user_id')
			->join('cate t3', 't1.cate_id = t3.cate_id')
			->order('t1.create_time desc')
			->where('t1.is_top', 1)
			->select();
		$this->assign('is_top', $is_top);

		/**
		 * 本周回帖周榜
		 */
		$reply = Db::name('reply')
			->alias('t1')
			->field('count(*) cn,t2.face,t2.nickname,t2.user_id')
			->join('user t2', 't1.user_id = t2.user_id')
			->group('t2.user_id')
			->order('cn desc')
			->select();
		$this->assign('reply', $reply);

		/**
		 * 按回复量排序取10条
		 */
		$week_hot = Question::order('reply_num desc')->limit(10)->select();
		$this->assign('week_hot', $week_hot);

		/**
		 * 签到方法
		 */
		$res = Sign::get(['user_id' => session('user_id')]);
		if ($res && time() - $res->sign_time <= 86400) {
			$this->assign('time', time());
		}
		$this->assign('sign', $res);
		$this->assign('title', '主页');
		return $this->fetch();
	}
}
